package com.scisoft.scan.control.shelves;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.data.QueryPageBean;
import com.scisoft.scan.data.depot.AreaBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.data.depot.WarehouseBean;
import com.scisoft.scan.data.shelves.ShelvesInfoBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper_Depot;
import com.scisoft.scan.ws.WebServiceHelper_Shelves;

import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class ShelvesActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_add; //增加按钮
    private ImageView iv_query; //搜索按钮
    private Spinner spin_depot;//仓库列表控件
    private Spinner spin_area;//库区列表控件
    private ClearEditText et_bar;
    private List<String> depotList = new ArrayList<>();//仓库字典
    private List<WarehouseBean> depotBeanList = new ArrayList<>();//仓库字典
    private List<String> areaList = new ArrayList<>();//库区字典
    private List<AreaBean> areaBeanList = new ArrayList<>();//库区字典
    private int selectedDepotNo = 0;
    private int selectedAreaNo = 0;
    private boolean depotHasInited = false;

    //分页配置表
    private QueryPageBean pageBean = null;
    private int currentPage = 0;
    float lastY = 0;
    //货架分页显示控件
    ShelvesAdapter shelvesAdapter;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在

    @Override
    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_shelves);
        //仓库
        spin_depot = findViewById(R.id.spin_depot);
        spin_area = findViewById(R.id.spin_area);
        et_bar = findViewById(R.id.et_bar);
        et_bar.setText("");
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(ShelvesActivity.this, MainMenuActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
                finish();
            }
        });
        //增加
        iv_add = findViewById(R.id.iv_add);
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShelvesActivity.this, ShelvesAddActivity.class);
                startActivity(intent);
            }
        });
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryData(true, false,true);
            }
        });
        //数据
        mRefreshLayout = findViewById(R.id.swipe_layout);
        mRefreshLayout.setProgressViewEndTarget(true, 0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryData(true, false,true);
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        shelvesAdapter = new ShelvesAdapter(ShelvesActivity.this);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        shelvesAdapter.setItemLayout(R.layout.item_shelves, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        shelvesAdapter.setOnItemClickListener(new ShelvesAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ShelvesInfoBean shelvesInfoBean = shelvesAdapter.getItemData(position);
                if (shelvesInfoBean != null) {
                    Intent intent = new Intent(ShelvesActivity.this, ShelvesEditActivity.class);
                    intent.putExtra("data", shelvesInfoBean);
                    startActivity(intent);
                }
            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            shelvesAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(shelvesAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == shelvesAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    shelvesAdapter.changeMoreStatus(LOADING_MORE);
                    QueryData(false, false,true);
                } else {
                    shelvesAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });

        QueryData(true, false,true);
    }

    //查询新增数据追加到列表尾
    private void QueryData(boolean refresh, boolean depotChanged,boolean queryShelves) {
        CommonUtil.showPress(this);
        QueryTask queryTask = new QueryTask(ShelvesActivity.this, refresh, depotChanged, queryShelves);
        queryTask.execute();
    }

    //绑定数据
    private void BindData(Context context, List<ShelvesInfoBean> newData, boolean refresh, boolean depotChanged) {
        //货架
        if (!depotHasInited) {
            SetSpanDepot(context);
            SetSpanArea(context);
            depotHasInited = true;
        }
        if (depotChanged) {
            SetSpanArea(context);
        }
        shelvesAdapter.clearLeftMenuList();
        if (!refresh) {
            //数据
            if (newData.size() > 0) {
                shelvesAdapter.addMoreItem(newData);
            } else {
                shelvesAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            if (newData.size() > 0) {
                shelvesAdapter.clearAddItem(newData);
            } else {
                shelvesAdapter.clearAddItem(newData);
                shelvesAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //绑定仓库数据
    private void SetSpanDepot(Context context) {
        spin_depot = findViewById(R.id.spin_depot);
        for (int i = 0; i < depotBeanList.size(); i++) {
            depotList.add(depotBeanList.get(i).depotName);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, depotList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_depot.setAdapter(adapter2);
        spin_depot.setSelection(0, true);
        spin_depot.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDepotNo = position;
                QueryData(true, true,false);//仓库发生变化，货位同时需要发生变化，更新字典项
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //绑定货位数据
    private void SetSpanArea(Context context) {
        spin_area = findViewById(R.id.spin_area);
        areaList.clear();
        for (int i = 0; i < areaBeanList.size(); i++) {
            areaList.add(areaBeanList.get(i).areaName);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, areaList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_area.setAdapter(adapter2);
        spin_area.setSelection(0, true);
        spin_area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedAreaNo = position;
                QueryData(true, false,true);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //查询货架服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mrefresh = true;
        boolean mdepotChanged = false;
        boolean mqueryShelves = false;
        private List<ShelvesInfoBean> newData = new ArrayList<>();

        QueryTask(Context context, boolean refresh, boolean depotChanged,boolean queryShelves) {
            super();
            mcontext = context;
            mrefresh = refresh;
            mdepotChanged = depotChanged;
            mqueryShelves = queryShelves;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //初始化仓库
                if (!depotHasInited) {
                    //仓库字典项初始化
                    depotBeanList = WebServiceHelper_Depot.DEPOT_01();
                    selectedDepotNo = 0;
                    //库区字典项初始化
                    if (depotBeanList != null && depotBeanList.size() > 0) {
                        areaBeanList = WebServiceHelper_Depot.DEPOT_12(depotBeanList.get(selectedDepotNo).depotId);
                        selectedAreaNo = 0;
                    }
                }
                //仓库发生变化，获取也需要变化
                if (mdepotChanged) {
                    if (depotBeanList != null && selectedDepotNo >= 0 && selectedDepotNo < depotBeanList.size()) {
                        areaBeanList = WebServiceHelper_Depot.DEPOT_12(depotBeanList.get(selectedDepotNo).depotId);
                        selectedAreaNo = 0;
                    }
                }
                if(mqueryShelves){
                    //重新刷新
                    if (mrefresh) {
                        pageBean = null;
                    }
                    //查询货架
                    String depotId = depotBeanList.get(selectedDepotNo).depotId;
                    String areaId = areaBeanList.get(selectedAreaNo).areaId;

                    //第一次程序时需要先查询分页信息
                    if (pageBean == null) {
                        pageBean = WebServiceHelper_Shelves.SHELVES_07(depotId, areaId, et_bar.getUpperText().toString());
                        currentPage = 0;
                    }
                    //翻页
                    currentPage++;
                    //判断是否全部显示，如果没有就查询下一页
                    if (currentPage <= pageBean.pageCount) {
                        newData = WebServiceHelper_Shelves.SHELVES_01(depotId, areaId, et_bar.getUpperText().toString(), pageBean.pageSize, currentPage);
                    }
                    //超过最大页则返回
                    if (currentPage > pageBean.pageCount) {
                        currentPage = pageBean.pageCount;
                    }
                }

                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh, mdepotChanged);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //适配器相关功能
    class ShelvesAdapter extends CommonAdapter<ShelvesInfoBean> {

        //构造函数
        public ShelvesAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final ShelvesInfoBean shelvesInfoBean, int position) {
            TextView tv_shelvesName = holder.getView(R.id.tv_shelvesName);
            TextView tv_depotName = holder.getView(R.id.tv_depotName);
            //获取相应索引的ItemBean对象
            final ShelvesInfoBean bean = mList.get(position);
            //设置控件的对应属性值
            tv_shelvesName.setText(bean.shelvesName);
            tv_depotName.setText(bean.depotName + " , " + bean.areaName);
            //按钮
            TextView tv_delete = holder.getView(R.id.tv_delete);
            tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showPress(ShelvesActivity.this);
                    DeleteTask deleteTask = new DeleteTask(ShelvesActivity.this, bean);
                    deleteTask.execute();
                }
            });
        }
    }

    //删除服务
    class DeleteTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private ShelvesInfoBean shelvesInfoBean;
        private List<ShelvesInfoBean> newData = new ArrayList<>();

        DeleteTask(Context context, ShelvesInfoBean shelvesInfoBean) {
            super();
            mcontext = context;
            this.shelvesInfoBean = shelvesInfoBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Shelves.SHELVES_08(shelvesInfoBean.shelvesId);
                if (msg.contains("成功")) {
                    pageBean = null;
                    //查询货架
                    String depotId = depotBeanList.get(selectedDepotNo).depotId;
                    String areaId = areaBeanList.get(selectedAreaNo).areaId;
                    //第一次程序时需要先查询分页信息
                    if (pageBean == null) {
                        pageBean = WebServiceHelper_Shelves.SHELVES_07(depotId, areaId, et_bar.getUpperText().toString());
                        currentPage = 0;
                    }
                    //翻页
                    currentPage++;
                    //判断是否全部显示，如果没有就查询下一页
                    if (currentPage <= pageBean.pageCount) {
                        newData = WebServiceHelper_Shelves.SHELVES_01(depotId, areaId, et_bar.getUpperText().toString(), pageBean.pageSize, currentPage);
                    }
                    //超过最大页则返回
                    if (currentPage > pageBean.pageCount) {
                        currentPage = pageBean.pageCount;
                    }
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, true, false);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }
}
